package com.sunyard.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @author k3887
 * @Description
 * @date 2018-11-22 下午4:07:19
 */
public class JsonUtil {
    /**
     * Logger for this class
     */
    private static final Logger logger = LoggerFactory.getLogger(JsonUtil.class);

    /**
     * Description
     */
    private JsonUtil() {
    }

    /**
     * object to String
     *
     * @param obj
     * @return String
     */
    public static String ObjectToString(Object obj) {
        try {
            return JSON.toJSONString(obj, SerializerFeature.WriteMapNullValue);
        } catch (Exception e) {
            logger.error("object to json error", e);
        }
        return null;
    }

    /**
     * 将json string反序列化成对象
     *
     * @param json
     * @param valueType
     * @return
     */
    public static <T> T StringJsonToObject(String json, Class<T> valueType) {
        try {
            return JSON.parseObject(json, valueType);
        } catch (Exception e) {
            logger.error("json to object error", e);
        }
        return null;
    }

    /**
     * json对象转map
     */
    public static Map JsonToMap(JSONObject obj) {
        Map<String, Object> data = new HashMap<>();
        //循环转换
        Iterator it = obj.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, Object> entry = (Map.Entry<String, Object>) it.next();
            data.put(entry.getKey(), entry.getValue());
        }
        return data;
    }
}
